package cn.findviewbydream.aspect;

import cn.findviewbydream.utils.ResultUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import javax.validation.constraints.NotNull;

/**********************************
 * 工程：cn.findviewbydream.aspect
 * 作者：白雨濃 evil
 * 时间：17-4-17 下午5:09
 * 邮箱：evilbai@foxmail.com
 * 内容：表单验证AOP全局处理
 **********************************/
@Aspect
@Component
public class ValidErrorAspect
{
    //private static Logger logger = LoggerFactory.getLogger(ValidErrorAspect.class);

    @Around("execution(public * cn.findviewbydream.controller.*.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable
    {
        BindingResult result = null;
        Object[] args = joinPoint.getArgs();

        /*在参数中查找BindingResult*/
        if (args != null && args.length != 0)
            for (Object object : args)
                if (object instanceof BindingResult)
                {
                    result = (BindingResult) object;
                    break;
                }

        if (result != null && result.hasErrors())
        {
            FieldError fieldError = result.getFieldError();
            //String targetName = joinPoint.getTarget().getClass().getSimpleName();
            //String method = joinPoint.getSignature().getName();
            //logger.info("验证失败.控制器:{}, 方法:{}, 参数:{}, 属性:{}, 错误:{}, 消息:{}", targetName, method, fieldError.getObjectName(), fieldError.getField(), fieldError.getCode(), fieldError.getDefaultMessage());
            String firstCode = fieldError.getCode();

            if (isMissingParamsError(firstCode))
                return ResultUtil.error(0, fieldError.getDefaultMessage());
            else
                return ResultUtil.error(0, fieldError.getDefaultMessage());
        }
        return joinPoint.proceed();
    }

    private boolean isMissingParamsError(String code)
    {
        return code.equals(NotNull.class.getSimpleName()) ||
                code.equals(NotBlank.class.getSimpleName()) ||
                code.equals(NotEmpty.class.getSimpleName());
    }
}
